package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *订单相关业务实现
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private  AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private ShoppingCartMapper cartMapper;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * 添加事务注解
     * @return
     */
    @Transactional()
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1.处理业务异常，验证用户地址、购物车数据
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            //用户地址为空，抛出业务异常
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            //购物车为空，抛出业务异常
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //2.插入一条订单数据--返回订单ID
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        //orders.setUserName();
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));

        orderMapper.insert(orders);


        //3.插入多条订单明细数据--批量插入-在xml进行循环插入
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        //4.清空购物车数据
        shoppingCartMapper.deleteByID(shoppingCart);

        //5.返回订单数据
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setId(orders.getId());

        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 分页查询历史订单
     * @param pageQuery
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO pageQuery) {
        //设置分页参数
        PageHelper.startPage(pageQuery.getPage(),pageQuery.getPageSize());
        pageQuery.setUserId(BaseContext.getCurrentId());
        //查询历史订单数据
        Page<Orders> page = orderMapper.pageQuery(pageQuery);
        //查询历史订单明细数据，封装到OrderVO中
        List<OrderVO> orderList =  new ArrayList<>();
        for (Orders orders : page.getResult()) {
            Long orderId = orders.getId();
            //查询订单明细
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            orderList.add(orderVO);
        }

        return new PageResult(page.getTotal(),orderList);
    }

    /**
     * 根据id查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getById(Long id) {
        if (id != null){
            //查询订单基本信息
            Orders orders = orderMapper.getById(id);
            //查询订单明细
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            return orderVO;
        }else {
            return null;
        }
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
        /*
● 如果在待接单状态下取消订单，需要给用户退款
● 取消订单后需要将订单状态修改为“已取消”
         */
        //1.查询订单状态
        Orders orders = orderMapper.getById(id);

        //2.判断订单状态
        if (orders.getStatus() > Orders.TO_BE_CONFIRMED ){
            throw new OrderBusinessException("订单状态异常");
        }
        //2.1待付款状态，取消订单，无需退款
        //2.2待接单状态，取消订单，需要退款
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED){
            //调用微信支付退款接口
            try {
                weChatPayUtil.refund(
                        orders.getNumber(),//商户订单号
                        orders.getNumber(),//商户退款单号
                        new BigDecimal(0.01),//退款金额，单位 元
                        new BigDecimal(0.01)//原订单金额
                );
            } catch (Exception e) {
                e.printStackTrace();
                throw new OrderBusinessException("退款失败");
            }
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);

        }
        //3.更新订单状态,取消原因，取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);


    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //把订单明细数据查询出来，重新添加到购物车中
        //1.查询订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        //2.封装购物车数据
        List<ShoppingCart> shoppingCartList =new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = ShoppingCart.builder()
                    .userId(BaseContext.getCurrentId())
                    .image(orderDetail.getImage())
                    .name(orderDetail.getName())
                    .amount(orderDetail.getAmount())
                    .dishFlavor(orderDetail.getDishFlavor())
                    .number(orderDetail.getNumber())
                    .build();
            shoppingCartList.add(shoppingCart);
       }
        //3.批量添加到购物车
        shoppingCartMapper.insertBatch(shoppingCartList);



    }

    /**
     * 条件查询搜索订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        Page page = orderMapper.pageQuery(ordersPageQueryDTO);
        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);

//        return new PageResult(page.getTotal(),page.getResult());
    }
    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO statistics() {
        //sql:SELECT count(id) as total FROM orders WHERE status = 2
        //1.查询待接单的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        //2.查询待配送的订单数量
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        //3.查询派送中的订单数量
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        //3.封装成OrderStatisticsVO
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 商家接单--订单状态修改为已接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Long id = ordersConfirmDTO.getId();
        Orders orders = orderMapper.getById(id);
        //判断订单状态是否为待接单
        if(orders.getStatus()!=Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException("订单状态异常");
        }
        //订单状态修改为已接单
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);

    }

    /**
     * 商家拒单
     * 需要退款
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //1.获取订单信息
        Long id = ordersRejectionDTO.getId();
        Orders orders = orderMapper.getById(id);
        //2.判断订单状态为待接单
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED) {

            if (orders.getPayStatus() == Orders.PAID) {
                //调用微信支付退款接口
                try {
                    weChatPayUtil.refund(
                            orders.getNumber(),//商户订单号
                            orders.getNumber(),//商户退款单号
                            new BigDecimal(0.01),//退款金额，单位 元
                            new BigDecimal(0.01)//原订单金额
                    );
                } catch (Exception e) {
                    throw new OrderBusinessException("退款失败");
                }
            }
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);

            //3.更新订单状态,拒单原因，拒单时间
            orders.setStatus(Orders.CANCELLED);
            orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        }else {
            throw new OrderBusinessException("订单状态异常");

        }
    }

    /**
     * 商家派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getById(id);
        //判断订单状态是否为已接单
        if(orders.getStatus()!=Orders.CONFIRMED){
            throw new OrderBusinessException("订单状态异常");
        }
        //订单状态修改为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 订单完成
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getById(id);
        //判断订单状态是否为派送中
        if(orders.getStatus()!=Orders.DELIVERY_IN_PROGRESS){
            throw new OrderBusinessException("订单状态异常");
        }
        //订单状态修改为完成
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    /**
     * 管理端取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        Long id = ordersCancelDTO.getId();
        Orders orders = orderMapper.getById(id);
        //判断订单状态是否为待派送，派送中，已完成
        if(orders.getStatus()==Orders.CONFIRMED || orders.getStatus() == Orders.DELIVERY_IN_PROGRESS || orders.getStatus() == Orders.COMPLETED){
            //调用微信支付退款接口
            try {
                weChatPayUtil.refund(
                        orders.getNumber(),//商户订单号
                        orders.getNumber(),//商户退款单号
                        new BigDecimal(0.01),//退款金额，单位 元
                        new BigDecimal(0.01)//原订单金额
                );
            } catch (Exception e) {
                throw new OrderBusinessException("退款失败");
            }
            //订单状态修改为已取消
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason(ordersCancelDTO.getCancelReason());
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);

        }else {
            throw new OrderBusinessException("订单状态异常");
        }
    }
}
